package com.example.demo.servlet;

import com.example.demo.HelloServlet;
import com.example.demo.bean.NewsBean;
import com.example.demo.dao.NewsDao;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

/**
 * 1. 接收post网址 /newsAdd.jsp
 * 2. 接收到传递过来的新闻参数 新闻标题 新闻内容
 * 3。 完成新闻的添加
 * 4. 跳转到其他页面
 */

@WebServlet("/newsAdd.jsp")
public class NewsAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //会话中获取管理员昵称
        String user =  (String) req.getSession().getAttribute("User");//获取对话
        if (user == null || user.equals("")) {
            resp.sendRedirect(req.getContextPath() + "/login.jsp");//没登陆 跳转到登陆页面
            return;
        }
        String newsTitle = req.getParameter("NewsTitle");
        String newsContent = req.getParameter("NewsContent");
        NewsBean newsBean = new NewsBean();
        newsBean.setNewsTitle(newsTitle);
        newsBean.setNewsContent(newsContent);
        newsBean.setAdminName("admin");
        NewsDao newsDao = new NewsDao();
        newsDao.add(newsBean);
        // 在Servlet中调用使用网址跳转 请求结果对象
        resp.sendRedirect("news.jsp");// 参数是相对网址
    }
}
